<template>
  <el-drawer
    v-model="visible"
    title="手动匹配流水"
    direction="rtl"
    size="600px"
    :before-close="handleClose"
  >
    <div class="manual-match-dialog" v-if="transaction">
      <!-- 流水信息 -->
      <el-card class="transaction-info">
        <template #header>
          <div class="card-header">
            <span>流水信息</span>
          </div>
        </template>
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <span class="label">流水号:</span>
              <span class="value">{{ transaction.transactionId }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="label">付款方:</span>
              <span class="value">{{ transaction.payerName }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="label">交易金额:</span>
              <span class="value amount" :class="{ 'income': transaction.amount > 0, 'expense': transaction.amount < 0 }">
                {{ formatCurrency(transaction.amount) }}
              </span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="label">交易日期:</span>
              <span class="value">{{ formatDate(transaction.transactionDate) }}</span>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 匹配条件 -->
      <el-card class="match-conditions">
        <template #header>
          <div class="card-header">
            <span>匹配条件</span>
          </div>
        </template>
        <el-form :model="matchForm" label-width="100px">
          <el-form-item label="订单号">
            <el-input v-model="matchForm.orderId" placeholder="请输入订单号" />
          </el-form-item>
          <el-form-item label="买家姓名">
            <el-input v-model="matchForm.buyerName" placeholder="请输入买家姓名" />
          </el-form-item>
          <el-form-item label="订单金额">
            <el-input-number 
              v-model="matchForm.orderAmount" 
              :precision="2" 
              :step="0.01" 
              placeholder="请输入订单金额"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="下单时间">
            <el-date-picker
              v-model="matchForm.orderDate"
              type="date"
              placeholder="请选择下单时间"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 搜索结果 -->
      <el-card class="search-results" v-if="searchResults.length > 0">
        <template #header>
          <div class="card-header">
            <span>搜索结果</span>
            <el-button type="primary" link @click="searchOrders">重新搜索</el-button>
          </div>
        </template>
        <el-table :data="searchResults" highlight-current-row @current-change="handleSelectOrder">
          <el-table-column prop="orderId" label="订单号" width="180" />
          <el-table-column prop="buyerName" label="买家姓名" width="120" />
          <el-table-column prop="orderAmount" label="订单金额" width="120">
            <template #default="{ row }">
              <span class="amount" :class="{ 'income': row.orderAmount > 0, 'expense': row.orderAmount < 0 }">
                {{ formatCurrency(row.orderAmount) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="orderDate" label="下单时间" width="120">
            <template #default="{ row }">
              {{ formatDate(row.orderDate) }}
            </template>
          </el-table-column>
          <el-table-column label="匹配度" width="100">
            <template #default="{ row }">
              <el-tag :type="getMatchConfidenceType(row.confidence)">
                {{ row.confidence }}%
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button @click="searchOrders" type="primary">搜索订单</el-button>
        <el-button @click="confirmMatch" type="success" :disabled="!selectedOrder">确认匹配</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, computed, reactive } from 'vue'
import { ElMessage } from 'element-plus'

// 定义组件props
const props = defineProps<{
  modelValue: boolean
  transaction: any
}>()

// 定义组件emits
const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'match-success', transaction: any, order: any): void
}>()

// 响应式数据
const matchForm = reactive({
  orderId: '',
  buyerName: '',
  orderAmount: undefined as number | undefined,
  orderDate: ''
})

const searchResults = ref<any[]>([])
const selectedOrder = ref<any>(null)

// 计算属性
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 方法
const handleClose = () => {
  visible.value = false
  // 重置表单
  matchForm.orderId = ''
  matchForm.buyerName = ''
  matchForm.orderAmount = undefined
  matchForm.orderDate = ''
  searchResults.value = []
  selectedOrder.value = null
}

const searchOrders = () => {
  // 模拟搜索订单
  // 实际项目中这里应该调用API搜索订单
  const mockOrders = [
    {
      orderId: 'PO20230101001',
      buyerName: props.transaction.payerName,
      orderAmount: props.transaction.amount,
      orderDate: props.transaction.transactionDate,
      confidence: 95
    },
    {
      orderId: 'PO20230101002',
      buyerName: props.transaction.payerName + '公司',
      orderAmount: props.transaction.amount,
      orderDate: props.transaction.transactionDate,
      confidence: 85
    },
    {
      orderId: 'PO20230101003',
      buyerName: '某' + props.transaction.payerName.slice(1),
      orderAmount: props.transaction.amount * 0.9,
      orderDate: props.transaction.transactionDate,
      confidence: 75
    }
  ]
  
  searchResults.value = mockOrders
  selectedOrder.value = null
  ElMessage.info('搜索完成，找到 ' + mockOrders.length + ' 个匹配的订单')
}

const handleSelectOrder = (row: any) => {
  selectedOrder.value = row
}

const confirmMatch = () => {
  if (!selectedOrder.value) {
    ElMessage.warning('请先选择要匹配的订单')
    return
  }
  
  // 触发匹配成功事件
  emit('match-success', props.transaction, selectedOrder.value)
  ElMessage.success('匹配成功')
  handleClose()
}

// 工具函数
const formatCurrency = (amount: number) => {
  const absAmount = Math.abs(amount)
  const sign = amount >= 0 ? '' : '-'
  return sign + '¥' + absAmount.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })
}

const formatDate = (date: string) => {
  return date.split('-').slice(1).join('-')
}

const getMatchConfidenceType = (confidence: number) => {
  if (confidence >= 90) return 'success'
  if (confidence >= 70) return 'warning'
  return 'info'
}
</script>

<style scoped lang="scss">
.manual-match-dialog {
  .transaction-info,
  .match-conditions,
  .search-results {
    margin-bottom: 20px;
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-weight: 600;
    }
    
    .info-item,
    .form-item {
      display: flex;
      margin-bottom: 12px;
      
      .label {
        width: 80px;
        font-weight: 500;
        color: #606266;
      }
      
      .value {
        flex: 1;
        color: #1f2d3d;
        
        &.amount {
          font-weight: 600;
          
          &.income {
            color: #67c23a;
          }
          
          &.expense {
            color: #f56c6c;
          }
        }
      }
    }
  }
}

.dialog-footer {
  text-align: right;
}
</style>